package com.cojson;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.File;

public class Response {

    private static final int BUFFER_SIZE = 1024;
    private Request request;
    private OutputStream output;

    public Response(OutputStream os){
        this.output = os;
    }

    public void setRequest(Request request){
        this.request = request;
    }

    public void sendStaticResource() throws IOException {
        byte[] bs = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        try{
            File file = new File(HttpServer.WEB_ROOT,request.getUri());
            if(file.exists()){
                String successMessage = "HTTP/1.1 200 OK\r\n" +
                        "Server: SSC\r\n"+
                        "Content-Type: text/html\r\n"+
                        "\r\n";
                output.write(successMessage.getBytes());
                fis = new FileInputStream(file);
                int ch = fis.read(bs,0,BUFFER_SIZE);
                while( ch != -1){
                    output.write(bs,0,ch);
                    ch = fis.read(bs,0,BUFFER_SIZE);
                }
            }else{
                String errorMessage ="HTTP/1.1 404 File Not Found\r\n"+
                        "Content-Type: text/html\r\n"+
                        "Content-Length: 23\r\n"+
                        "\r\n"+
                        "<h1>404 File Note Found!</h1>";
                output.write(errorMessage.getBytes());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(fis != null){
                fis.close();
            }
        }
    }
}
